module div_datapath(clk,reset,rdy,dividend,
    divisor,run,wrg,fsh,quo,rem);
     
    parameter n = 32;
    parameter m = 16;
    
    input clk,reset,rdy,run;
    input [n-1:0] dividend,divisor;
    output fsh,wrg;
    output [n+m-1:0] quo;
    output [n-1:0] rem;
    wire clk,reset,rdy;
    reg fsh,wrg,ok;
    wire [n-1:0] dividend,divisor;
    reg [n-1:0] rem;
    reg [n+m-1:0] quo;
    
    reg [2*n-1:0] s;
    reg [2*n-1:0] D;
    reg [5:0] k;
    reg flag;

    always @ (posedge clk or negedge reset)
    begin
        if(!reset)
        begin
            fsh <= 0;
            quo <= 0;
            rem <= 0;
            wrg <= 0;
        end
        else if(divisor == 0) wrg <= 1;
        else begin
           if(rdy) begin
               flag <= 1;
               s <= {{(n-1){1'b0}},dividend,1'b0};
               D <= {divisor,{n{1'b0}}};
               k <= m+n;
           end
           else if(run)
           begin
               if(k==0) begin
                   fsh <= 1;
                   s <= (s>>n/2);
                   rem <= s;
               end
               else if(D[2*n-1]==0 && (D[2*n-2]==0)) 
               begin
                   s <= (s<<1);
                   D <= (D<<1);
               end
               else if(flag)
               begin
                   if(s[2*n-1]==0 && (s[2*n-2]==0))
                   begin
                      s <= (s<<1);
                      k <= k-1;
                      flag <= 1;
                  end 
                  else flag <= 0;
               end
               else begin
                   if(s >= D) 
                   begin
                       quo <= ((quo<<1)+1);
                       s <= ((s-D)<<1);
                       k <= k-1;
                   end
                   else begin
                       quo <= (quo<<1);
                       s <= (s<<1);
                       k <= k-1;
                   end
                end
           end
       end
    end
endmodule  